#ifndef __PROCESS_POOL_HPP__
#define __PROCESS_POOL_HPP__

#include <iostream>
#include <vector>
#include <unistd.h>
#include <cstdlib>
#include <string>
#include "Task.hpp"
#include <sys/wait.h>

// 先描述
class Channel
{
public:
    Channel(int wfd, pid_t id) : _wfd(wfd), _subid(id)
    {
        _name = "channel-" + std::to_string(_wfd) + "-" + std::to_string(_subid);
    }
    std::string Name() { return _name; }
    void send(int taskcode)
    {
        int n = write(_wfd, &taskcode, sizeof(taskcode));
        (void)n;
    }
    void Close()
    {
        close(_wfd);
    }
    void Wait()
    {
        pid_t rid = waitpid(_subid, nullptr, 0);
        (void)rid;
    }
    ~Channel()
    {
    }

private:
    int _wfd; // 信道写端
    pid_t _subid;
    std::string _name;
    int _loadnum;
};

// 再组织
class ChannelManager
{
public:
    ChannelManager(int next = 0) : _next(next) {}
    void InsertChannel(int wfd, pid_t subid)
    {
        _channels.emplace_back(wfd, subid);
        // Channel c(wfd, subid);
        // _channels.push_back(c);
    }
    void Print()
    {
        for (auto &e : _channels)
        {
            std::cout << e.Name() << std::endl;
        }
    }
    // 选择一个信道来执行task
    Channel &SelectChannel()
    {
        Channel &c = _channels[_next];
        _next++;
        _next %= 5;
        return c;
    }
    void StopProcess()
    {
        for (auto &Channel : _channels)
        {
            Channel.Close();
            std::cout << "关闭：" << Channel.Name() << std::endl;
        }
    }
    void WaitSubProcess()
    {
        for (auto &Channel : _channels)
        {
            Channel.Wait();
            std::cout << "回收子进程：" << Channel.Name() << std::endl;
        }
    }
    ~ChannelManager() {}

private:
    std::vector<Channel> _channels;
    int _next;
};

const int defaultnum = 5;
class ProcessPool
{
public:
    ProcessPool(int num) : _process_num(num)
    {
        _tm.Register(PrintLog);
        _tm.Register(download);
        _tm.Register(submit);
    }

    void work(int rfd)
    {

        while (true)
        {
            int code = 0;
            ssize_t n = read(rfd, &code, sizeof(code));
            if (n > 0)
            {
                if (n != sizeof(code))
                {
                    continue;
                }
                // 读取四个字节成功
                // std::cout << "子程序[" << getpid() << "]收到一个任务码：" << code << std::endl;
                _tm.Excute(code);
            }
            else if (0 == n)
            {
                // 写端关闭，子进程退出
                std::cout << "子进程退出,我的pid:" << getpid() << std::endl;
                break;
            }
            else
            {
                std::cout << "程序错误" << std::endl;
                break;
                // 读取错误
            }
        }

        // while (1)
        // {
        //     std::cout << "我是子进程,我的rfd:" << rfd << std::endl;
        //     sleep(1);
        // }
    }
    bool Create()
    {
        // 创建信道
        for (int i = 0; i < _process_num; i++)
        {
            int pipefd[2] = {0};
            int n = pipe(pipefd);
            if (n < 0)
            {
                return false;
            }
            // 2.创建子进程
            pid_t subid = fork();
            if (subid < 0)
                return false;
            // 创建成功
            else if (subid == 0)
            {
                // 子进程

                // 关闭不需要的文件描述符
                close(pipefd[1]);
                work(pipefd[0]);
                close(pipefd[0]);
                exit(0);
            }
            else
            {
                // 父进程
                close(pipefd[0]); // 写端，pipefd[1]
                _cm.InsertChannel(pipefd[1], subid);
            }
        }
        return true;
    }
    void run()
    {
        // 1.选择一个任务
        int taskcode = _tm.Code();

        // 2.选择一个信道
        auto &c = _cm.SelectChannel();
        std::cout << "选择了一个子进程" << c.Name() << std::endl;

        // 3.发送任务
        c.send(taskcode);
        std::cout << "发送了一个任务码：" << taskcode << std::endl;
    }

    void debug()
    {
        _cm.Print();
    }

    void Stop()
    {
        // 关闭父进程的写端，work读到0
        _cm.StopProcess();
        _cm.WaitSubProcess();
        // 回收子进程
    }
    ~ProcessPool() {}

private:
    ChannelManager _cm;
    int _process_num;
    TaskManager _tm;
};

#endif